package org.microser.gataway.zuul.filter;


import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.microser.gataway.zuul.config.SecurityFilter;
import org.microser.gataway.zuul.utils.MatchingURI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 第一个过滤器，所有请求都回过滤
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-11-24 9:07
 */
@Slf4j
public class FirstFilter extends DefinedZuulFilter {

    @Override
    public String filterType() {
        return FILTERTYPE_PRE;
    }

    @Override
    public int filterOrder() {
        return 0;// 优先级为0，数字越大，优先级越低
    }

    @Autowired
    private SecurityFilter securityFilter;

    @Override
    public boolean shouldFilter() {
        return true;// 是否执行该过滤器，此处为true，说明需要过滤
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = currentContext.getRequest();

        //如果是options请求直接放过
        if(request.getMethod().matches(HttpMethod.OPTIONS.name())){
            return true;
        }

        //获取uri
        String requestURI = request.getRequestURI();
        log.info("前缀过滤器："+requestURI);

        //获取security所有过滤器
        LinkedHashMap<String, DefinedZuulFilter> filterMap = securityFilter.getFilter();
        //获取放行uri
        LinkedHashMap<String,String> uriMap = securityFilter.getUri();
        for(Map.Entry<String,String> entry : uriMap.entrySet()){
            //判断当前请求路径是否放行
            if(MatchingURI.equlasUri(entry.getKey(),requestURI)){
                for(Map.Entry<String,DefinedZuulFilter> filter:filterMap.entrySet()){
                    //请求路径的过滤器（如anon、jwtToken）是否与filter的key（anon、jwtToken）相等
                    if(entry.getValue().equals(filter.getKey())){
                        log.info(filter.getKey()+" : 执行");
                        if(filter.getValue()!=null){
                            filter.getValue().setFlag(true);
                        }
                        return null;
                    }
                }
            }
        }
        log.info("不执行过滤器 ：放行");
        return null;
    }



}
